package app.caihan.wanandroid.ui.wxarticle

import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.viewpager2.adapter.FragmentStateAdapter
import app.caihan.scframe.databind.DataBindingConfig
import app.caihan.wanandroid.BR
import app.caihan.wanandroid.R
import app.caihan.wanandroid.base.WanBaseFragment
import app.caihan.wanandroid.databinding.FragmentWxArticleBinding
import com.google.android.material.tabs.TabLayoutMediator

/**
 * 公众号
 *
 * @author Seven-C
 * @date 2020/8/11
 */
class WxArticleFragment : WanBaseFragment<WxArticleFragmentModel>() {

    private val tabLayout by lazy { (getBinding() as FragmentWxArticleBinding).tabLayout }
    private val projectViewPager by lazy { (getBinding() as FragmentWxArticleBinding).projectViewPager }

    companion object {
        fun newInstance(): WxArticleFragment {
            return WxArticleFragment()
        }
    }


    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(BR.vm)
    }

    override fun bindLayoutId(): Int {
        return R.layout.fragment_wx_article
    }

    override fun initView(savedInstanceState: Bundle?) {
    }

    override fun lazyLoadData() {
        mViewModel.getWxArticleChapters()
    }

    override fun createObserver() {
        mViewModel.apply {
            chapters.observe(this@WxArticleFragment, Observer {
                chapters.value?.let {
                    projectViewPager.adapter =
                        object : FragmentStateAdapter(this@WxArticleFragment) {

                            override fun getItemCount() = it.size

                            override fun createFragment(position: Int) =
                                ChapterFragment.newInstance(it[position].id)

                        }
                    TabLayoutMediator(tabLayout, projectViewPager) { tab, position ->
                        tab.text = it[position].name
                    }.attach()
                }
            })
        }
    }
}